import time
from concurrent.futures import ThreadPoolExecutor, as_completed
import os
from datetime import datetime,timedelta
from pathlib import Path

from concurrent__remove_noise import concurrent_remove_noise
from concurrent_recog_block import process_dxf_file, filter_lists_by_excel_header, operate_original_dxf
from utils import process_inserts
from utils import delete_old_files,start_fentu

def main(dxf_files,origin_dxf_path,operation):
    excel_path_list = []
    df_result = []
    dxf_json_resut = []
    with ThreadPoolExecutor(max_workers=10) as executor:
        futures = [executor.submit(process_dxf_file, dxf) for dxf in dxf_files]
        for future in as_completed(futures):
            result = future.result()[0]
            df_result.append(future.result()[1])
            dxf_json_resut.append(future.result()[2])
            excel_path_list.append(result)

    excel_l, df_l, dxf_l = filter_lists_by_excel_header(excel_path_list, df_result, dxf_json_resut,operation)
    print("\n📂 所有分图结果收集完毕\n")
    operate_original_dxf(excel_l, df_l, dxf_l, origin_dxf_path,operation)

if __name__ == "__main__":
    now = datetime.now()
    delete_old_files(r'E:\cadsecond-processing\output', cutoff_time=now - timedelta(minutes=5))
    delete_old_files(r'E:\cadsecond-processing\output_excel', cutoff_time=now - timedelta(minutes=5))
    delete_old_files(r'E:\cadsecond-processing\updated_graph', cutoff_time=now - timedelta(minutes=5))
    delete_old_files(r'E:\cadsecond-processing\清除后的图纸', cutoff_time=now - timedelta(minutes=5))
    now = time.time()
    SRC_FILE = r"E:\cadsecond-processing\drawingLibrary\嘉兴海宁全1.dxf"
    OUT_FOLDER = r"E:\cadsecond-processing\output"
    BLOCK_NAME = "model1_A3"

    Path(OUT_FOLDER).mkdir(exist_ok=True)
    #分图处理
    dxf_sub_graph_files = start_fentu(OUT_FOLDER, SRC_FILE, BLOCK_NAME)
    # 去噪后的图纸
    noise_remove_dxf_file = concurrent_remove_noise(dxf_sub_graph_files)
    origin_dxf_path = 'E:\cadsecond-processing\drawingLibrary\嘉兴海宁全1.dxf'
    operation = {'target_device_name':'壁挂空调','insert_position':{"x": 0, "y": 0},'mode':'add','new_device_name': None}#'delete'|'move'|'replace'
    main(noise_remove_dxf_file,origin_dxf_path,operation)
    end = time.time()
    print(f'总时长为：{end-now}')